package  
{
	import flash.filesystem.File;
	import flash.filesystem.FileMode;
	import flash.filesystem.FileStream;
	/**
	 * ...
	 * @author WLDragon
	 */
	public class GetMixFields 
	{
		private var fieldsSet:Object;
		private var stream:FileStream = new FileStream();
		
		public function GetMixFields() 
		{
			
		}
		
		/**
		 * 开始提取需要混淆的字段，类名、方法名和变量名
		 * @param	files 需要提取源的文件
		 * @param	completeCallBack 提取结束后回调 function(str:String)
		 */
		public function begin(files:Array, completeCallBack:Function):void
		{
			fieldsSet = { };
			getFolds(files, "");
			
			var a:Array = [];
			for (var k:String in fieldsSet) {
				a.push(k);
			}
			
			completeCallBack(a.join(","));
		}
		
		private function getFolds(files:Array, parentFold:String):void
		{
			for (var i:int = 0; i < files.length; i++) {
				var f:File = files[i];
				if (f.isDirectory) {
					var p:String = parentFold + f.name + ".";
					getFolds(f.getDirectoryListing(), p);
				} else {
					getFieldsFromFile(f, parentFold);
				}
			}
		}
		
		private function getFieldsFromFile(file:File, parentFold:String):void
		{
			if (file.name.indexOf(".as") == -1) return;
			
			if (parentFold != "") {
				var p:String = parentFold.substr(0, parentFold.length - 1);
				if(fieldsSet[p] == undefined) fieldsSet[p] = 0;//记录包名
			}
			
			fieldsSet[file.name.replace(".as", "")] = 0;//记录类名
			
			stream.open(file, FileMode.READ);
			var txt:String = stream.readUTFBytes(stream.bytesAvailable);
			stream.close();
			
			var a:Array = txt.indexOf("\r\n") > -1 ? txt.split("\r\n") : txt.split("\n");//兼容CRLF和LF分行的文件
			for (var i:int = 0, n:int = a.length; i < n; i++) {
				var s:String = a[i];
				if (s.indexOf("private") > -1 || s.indexOf("public") > -1) {
					var i1:int = s.indexOf(" var ");
					var i2:int = s.indexOf(":");
					var i3:int = s.indexOf(" function ");
					var i4:int = s.indexOf("(");
					var i5:int = s.indexOf(" const ");
					var i6:int = s.indexOf(" get ");
					var i7:int = s.indexOf(" set ");
					if (i1 > -1 && i2 > i1) {//提取变量名
						fieldsSet[getFieldFromText(s, i1 + 5, i2 - 1)] = 0;//使用键而不是值来保存结果是为了过滤重复字段
					}else if (i6 > -1 && i4 > i6) {//提取get方法名
						fieldsSet[getFieldFromText(s, i6 + 5, i4 - 1)] = 0;
					}else if (i7 > -1 && i4 > i7) {//提取set方法名
						fieldsSet[getFieldFromText(s, i7 + 5, i4 - 1)] = 0;
					}else if (i3 > -1 && i4 > i3) {//提取方法名和类名
						fieldsSet[getFieldFromText(s, i3 + 10, i4 - 1)] = 0;
					}else if (i5 > -1 && i2 > i5) {//提取常量
						fieldsSet[getFieldFromText(s, i5 + 7, i2 - 1)] = 0;
					}
				}
			}
		}
		
		private function getFieldFromText(str:String, begin:int, end:int):String
		{
			while (str.charCodeAt(begin) == 32) {//去掉多余的空格
				begin++;
			}
			while (str.charCodeAt(end) == 32) {//去掉多余的空格
				end--;
			}

			return str.substring(begin, end + 1);
		}
	}

}